//
//  CYLocationManager.m
//  cyjf
//
//  Created by tauCross on 2017/9/20.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYLocationManager.h"

#import <AFHTTPSessionManager.h>



@interface CYLocationManager ()

@property(nonatomic, strong)AFHTTPSessionManager *sessionManager;
@property(nonatomic, assign)BOOL channelInfoUploading;

@end


@implementation CYLocationManager

+ (instancetype)standardManager
{
    static CYLocationManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[CYLocationManager alloc] init];
    });
    return manager;
}

- (instancetype)init
{
    self = [super init];
    if(self)
    {
        self.sessionManager = [AFHTTPSessionManager manager];
        self.sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
        [self fetchLocationWithIP];
    }
    return self;
}

- (void)fetchLocationWithIP
{
    @weakify(self);
    [self.sessionManager POST:@"http://restapi.amap.com/v3/ip" parameters:@{@"key":@"83e0a3349228f36df10864fc0ddf16f7"} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self);
        if([responseObject isKindOfClass:[NSDictionary class]])
        {
            NSString *city = responseObject[@"city"];
            NSString *province = responseObject[@"province"];
            if([city isKindOfClass:[NSString class]] && city.length && [province isKindOfClass:[NSString class]] && province.length)
            {
                if(self.city == nil && self.province == nil)
                {
                    self.city = city;
                    self.province = province;
                    [self uploadChannelInfo];
                }
            }
        }
        if(self.city == nil)
        {
            [self performSelector:@selector(fetchLocationWithIP) withObject:nil afterDelay:2];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        @strongify(self);
        if(self.city == nil)
        {
            [self performSelector:@selector(fetchLocationWithIP) withObject:nil afterDelay:2];
        }
    }];
}

- (void)uploadChannelInfo
{
    if(self.channelInfoUploading)
    {
        return;
    }
    self.channelInfoUploading = YES;
    [CYStandardDataAPI channel_saveLogWithComplete:^(CYResponse *response) {
        if(response.code != 0)
        {
            self.channelInfoUploading = NO;
        }
    }];
}

@end
